package models;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import play.cache.Cache;

import siena.Generator;
import siena.Id;
import siena.Model;
import siena.Query;
import siena.Table;

@Table(value = "category")
public class CategoryModel extends Model implements Serializable{

	@Id(Generator.AUTO_INCREMENT)
	public Long id;
	
	public String name;
	public String alias;
	public String description;
	public String imagePath;
	public String box;//dongphuc,bhld
	
	public CategoryModel(String name, String alias,
			String description, String imagePath, String box) {
		super();
		this.name = name;
		this.alias = alias;
		this.description = description;
		this.imagePath = imagePath;
		this.box = box;
	}

	public static Query<CategoryModel> all(){
		return Model.all(CategoryModel.class);
	}
	
	public static List<CategoryModel> listCategoies(){
		if(all().fetch().size() > 0)
			return all().fetch();
		else
			return init();
	}
	
	//return list dongphuc
	public static List<CategoryModel> listDongPhuc(){
		if(Cache.get(util.Contant.DONG_PHUC) != null){
			return Cache.get(util.Contant.DONG_PHUC, List.class);
		}
		List<CategoryModel> list = all().filter("box", util.Contant.DONG_PHUC).fetch();
		Cache.set(util.Contant.DONG_PHUC, list);
		return list;
	}
	
	//return list bhld
	public static List<CategoryModel> listBHLD(){
		if(Cache.get(util.Contant.BHLD) != null){
			return Cache.get(util.Contant.BHLD, List.class);
		}
		List<CategoryModel> list = all().filter("box", util.Contant.BHLD).fetch();
		Cache.set(util.Contant.BHLD, list);
		return list;
	}
	
	private static List<CategoryModel> init(){
		List<CategoryModel> list = new ArrayList<CategoryModel>();
		for( int i = 0; i < 10; i ++){
			CategoryModel categoryModel = new CategoryModel("test" + i,  "Description " + i, "alias "  + i,  "shortImage " + i, "bhld");
			list.add(categoryModel);
		}
		return list;
	}
	
	//get Cateogry follow Id
	public static CategoryModel getCategoryFollowId(long id){
		if(id != 0){
			return all().getByKey(id);
		}
		return null;
	}
	
	//delete Category follow Id
	public static void deleteCategory(long id){
		CategoryModel categoryModel = getCategoryFollowId(id);
		if(categoryModel != null){
			categoryModel.delete();
		}
	}
}
